package com.acwing.partition12;

import java.io.*;

/**
 * @author `RKC`
 * @date 2021/12/31 20:19
 */
public class AC1117单词接龙 {

    private static final int N = 25;
    private static int n = 0, answer = 0;
    private static String[] words = new String[N];
    //overlap[i][j]表示字符串words[i]和words[j]的重叠部分，其中words[i]在前，words[j]在后
    private static int[][] overlap = new int[N][N];
    //used[i]记录当前words[i]在接龙中使用的次数
    private static int[] used = new int[N];

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        n = Integer.parseInt(reader.readLine());
        for (int i = 0; i < n; i++) words[i] = reader.readLine();
        char start = reader.readLine().charAt(0);
        //预处理出来任意两个字符串的重叠部分
        init();
        //从每个首字符是start的单词出发进行搜索
        for (int i = 0; i < n; i++) {
            if (words[i].charAt(0) == start) {
                dfs(words[i], i);
            }
        }
        writer.write(answer + "\n");
        writer.flush();
    }

    private static void init() {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                String s1 = words[i], s2 = words[j];
                for (int k = 1; k < Math.min(s1.length(), s2.length()); k++) {
                    if (s1.substring(s1.length() - k).equals(s2.substring(0, k))) {
                        //要让单词接龙尽量长，就尽量让重叠部分小
                        overlap[i][j] = k;
                        break;
                    }
                }
            }
        }
    }

    private static void dfs(String word, int last) {
        answer = Math.max(answer, word.length());
        used[last]++;
        for (int i = 0; i < n; i++) {
            //如果有重叠且使用的次数小于2，就继续拼接搜索
            if (overlap[last][i] > 0 && used[i] < 2) {
                dfs(word + words[i].substring(overlap[last][i]), i);
            }
        }
        used[last]--;
    }
}
